package com.gdut.huayan.utils;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gdut.huayan.entity.dto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class WebJsonUtils {

    @Autowired
    private RestTemplate restTemplate;

    public static void write(HttpServletResponse resp, Result result) throws IOException {
        resp.setContentType("application/json;charset=UTF-8");
        String token = new ObjectMapper().writeValueAsString(result);
        resp.getWriter().append(token);
    }

    public JSONObject sendPost(String url, JSONObject json){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(json.toJSONString(), headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, entity, String.class);
        return JSONObject.parseObject(responseEntity.getBody());
    }

    public JSONObject sendGet(String url){
        ResponseEntity<String> resp = restTemplate.getForEntity(url, String.class);
        return JSONObject.parseObject(resp.getBody());
    }

}
